<template>
  <div class="create-post-page">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>发布新帖子</span>
      </div>
      <el-form :model="form" ref="form" :rules="rules" label-width="68px">
        <el-form-item label="标题" prop="postTitle">
          <el-input
            v-model="form.postTitle"
            placeholder="请输入帖子标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="postContent">
          <editor v-model="form.postContent" :min-height="300" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPost">发布</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  listPosts,
  getPosts,
  delPosts,
  addPosts,
  updatePosts,
} from "@/api/teahouse/posts";
export default {
  name: "CreatePostPage",
  data() {
    return {
      form: {
        postTitle: "",
        postContent: "",
      },
      rules: {
        postTitle: [
          { required: true, message: "请输入帖子标题", trigger: "blur" },
        ],
        postContent: [
          { required: true, message: "请输入帖子内容", trigger: "blur" },
          { min: 10, message: "帖子内容至少为 10 个字符", trigger: "blur" },
        ],
      },
    };
  },

  methods: {
    submitPost() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.userId = this.$store.state.user.id;
          addPosts(this.form).then((res) => {
            this.$message({
              message: "发布成功，请等待审核",
              type: "success",
            });
          }).catch((error) => {
            this.$message({
              message: "发布失败, 请重试",
              type: "error",
            });
          });
          this.$router.push({ path: "/share" });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
.create-post-page {
  margin: 20px;
}
.box-card {
  max-width: 800px;
  margin: auto;
}
</style>
